<template>
<div class="advertisementList">
  <search-block>
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addAd">添加广告位</el-button>
    </template>
    <el-form inline :model="model" label-width="100px" @submit.native.prevent>
      <el-form-item label="广告位名称:">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns"
  >
    <el-table-column slot="isShow" label="启用" align="center" header-align="center" width="80">
      <template v-slot="{row}">
        <el-popconfirm
          :title="row.isShow === '1' ? `是否确认启用？` : `是否确认停用？`"
          @confirm="doEnable(row, row.isShow === '1')"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="row.isShow"
            active-value="0"
            inactive-value="1"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="scope">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editAd(scope.row)">编辑</el-button>
          <el-popconfirm
              title="是否确认删除该广告位？"
              @confirm="delAd(scope.row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    ref="form"
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="800px"
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
  </y-form>
</div>
</template>

<script>
export default {
  name: "advertisementList",
  inject: ['getDictNameSync'],
  computed: {
    getDataWay() {
      return {
        dataType: 'url',
        data: this.$api.applet.advertisementPage,
        param: this.model
      }
    },
    formColumns(){
      return [
        {
          label: "广告位名称",
          prop: "name",
          comp:{
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "广告位编码",
          prop: "type",
          comp:{
            compType: 'YCodeSelect',
            attrs:{
              disabled: this.forms.formsType === 'EDIT',
              dict: 'GGWBM'
            }
          }
        },
        {
          label: "广告位类型",
          prop: "commentsType",
          comp:{
            compType: 'YCodeSelect',
            attrs: {
              dict: 'cms_content_type'
            },
            listeners: {
              change: (function(val){
                this.forms.formModel.list = [];
              }).bind(this)
            }
          }
        },
        {
          label: "绑定CMS",
          prop: "list",
          comp:{
            compType: 'select',
            options: this.cmsList.filter(item => !this.forms.formModel.commentsType || item.contentType === this.forms.formModel.commentsType),
            attrs:{
              multiple: true
            }
          }
        },
        {
          label: "广告位描述",
          prop: "description",
          comp:{
            compType: 'input',
            attrs:{
              type: 'textarea',
              maxlength: 100,
              showWordLimit: true,
              autosize: {
                minRows: 3
              }
            }
          }
        }
      ]
    }
  },
  mounted(){
    this.$yAxios({
      url: this.$api.applet.queryCmsList,
      data: {}
    }, info => {
      this.cmsList = info.map(item => ({
        label: item.title,
        value: item.id,
        contentType: item.contentType
      }));
    })
  },
  data(){
    return{
      model: {
        name: '',
      },
      cmsList: [],
      columns: [{
        label: "名称",
        prop: "name",
        width: 120
      }, {
        label: "编码",
        prop: "type",
        width: 100,
        formatter: (function(row){
          return this.getDictNameSync(row.type, 'GGWBM');
        }).bind(this)
      }, {
        label: "类型",
        prop: "commentsType",
        width: 100,
        formatter: (function(row){
          return this.getDictNameSync(row.commentsType, 'cms_content_type');
        }).bind(this)
      },{
        label: "描述",
        prop: "description",
        minWidth: 300
      },{
        label: "启用",
        prop: "isShow",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加广告位',
          'EDIT': '编辑广告位'
        },
        formModel:{
          id: '',
          name: '',
          type: '',
          commentsType: '',
          description: '',
          list: []
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            name: [{required: true, message: "请输入广告位名称", trigger: "blur"}],
            type: [
              {required: true, message: "请选择广告位编码", trigger: "change"},
              {
                validator: (rule, value, callback) => {
                  this.$$validateCode(
                    this.$api.applet.validateAdvertisement,
                    {
                      id: this.forms.formModel.id,
                      type: this.forms.formModel.type
                    }, callback);
                },
                trigger: 'change'
              }
            ],
            commentsType: [{required: true, message: "请选择广告位类型", trigger: "change"}]
          }
        }
      }
    }
  },
  methods: {
    resetForm() {
      Object.keys(this.forms.formModel).map(key => {
        this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
    },
    addAd(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    editAd(row){
      this.forms.formsType = 'EDIT';
      this.$yAxios({
        url: this.$api.applet.queryAdvertisement,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.forms.currentForm = info.advertisementSpace;
        this.forms.currentForm.list = info.ids;
        this.resetForm();
        this.forms.showForm = true;
      })
    },
    delAd(row){
      this.$yAxios({
        url: this.$api.applet.removeAdvertisement,
        data:{
          ids: [row.id]
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({ isShow: '0' }, form);
      }
      let obj = {
        advertisementSpace: newForm,
        list: newForm.list
      }
      this.$delete(newForm, 'list');
      newForm = obj;
      this.$yAxios({
        url: this.$api.applet.saveAdvertisement,
        data: newForm,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    doEnable(row, bool){
      let url = this.$api.applet.switchAdvertisement;
      this.$yAxios({
        url,
        data:{
          id: row.id,
          isShow: bool ? '0' : '1'
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: bool ? '启用成功' : '禁用成功'
        });
        this.search();
      })
    }
  }
}
</script>

<style scoped>

</style>